package com.mlink.ai.chat.utils

import android.content.Context
import android.os.Build
import android.os.LocaleList
import com.tencent.mmkv.MMKV
import java.util.Locale

object LanguageUtils {

    private const val KEY_CODE_LANGUAGE = "key_code_language"

    fun changeLanguage(context: Context, code: String, persistence: Boolean) {
        try {
            val list = code.split(",")
            val locale = if (list.size >= 2) {
                Locale(list[0], list[1])
            } else {
                // 处理 1.0.7 之前版本升级的情况
                Locale(code.substring(0, 2))
            }
            val resources = context.resources
            val metrics = resources.displayMetrics
            val configuration = resources.configuration
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                configuration.setLocale(locale)
                configuration.setLocales(LocaleList(locale))
                context.createConfigurationContext(configuration)
            } else {
                configuration.setLocale(locale)
            }
            resources.updateConfiguration(configuration, metrics)
            if (persistence) {
                MMKV.defaultMMKV().encode(KEY_CODE_LANGUAGE, code)
            }
        } catch (_: Exception) {
            // do nothing now
        }
    }

    fun getCurrentLanguageCode() = MMKV.defaultMMKV().decodeString(KEY_CODE_LANGUAGE)

    fun isLanguageSet() = getCurrentLanguageCode() != null

    fun getCurrentLocale(): Locale {
        if (isLanguageSet()) {
            val code = getCurrentLanguageCode()!!
            val list = code.split(",")
            return if (list.size >= 2) {
                Locale(list[0], list[1])
            } else {
                // 处理 1.0.7 之前版本升级的情况
                Locale(code.substring(0, 2))
            }
        }
        return Locale.getDefault()
    }
}